package x.ovo.wechat.bot.http.request.core;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.ReUtil;
import x.ovo.wechat.bot.common.Constant;
import x.ovo.wechat.bot.common.entity.SyncCheckResult;
import x.ovo.wechat.bot.common.http.request.ApiRequest;
import x.ovo.wechat.bot.common.http.session.LoginSession;

import java.util.List;
import java.util.function.Function;

/**
 * 心跳检查请求
 *
 * @author ovo, created by 2024/05/03
 */
public class SyncCheckRequest extends ApiRequest<SyncCheckResult> {

    public SyncCheckRequest(LoginSession session) {
        super(session);
//        Map<String, String> map = super.addHeader("Referer", "https://wx.qq.com/")
//                .getHeaders();
//        map.remove("Content-Type");
//        map.remove("client-version");
//        map.remove("extspam");
//        map.remove("Origin");
    }

    @Override
    public String getUrl() {
        return UrlBuilder.of(this.session.getUrl())
                .addPath(Constant.SYNCCHECK)
                .addQuery("r", System.currentTimeMillis())
                .addQuery("skey", this.session.getSKey())
                .addQuery("sid", this.session.getWxSid())
                .addQuery("uin", this.session.getWxUin())
                .addQuery("deviceid", this.session.getDeviceId())
                .addQuery("synckey", this.session.getSyncCheckKey())
                .addQuery("_", System.currentTimeMillis())
                .build();
    }

    @Override
    public Function<String, SyncCheckResult> responseHandler() {
        return s -> {
            List<String> list = ReUtil.getAllGroups(Constant.SYNC_CHECK_PATTERN, s);
            return new SyncCheckResult(Integer.parseInt(list.get(1)), Integer.parseInt(list.get(2)));
        };
    }
}
